package com.fysports.web.handler;

import com.jfinal.handler.Handler;
import com.fysports.web.kit.umeditor.DownLoadFileParse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * /down公共路由 处理所有/down路径下路由信息
 * Created by konbluesky on 14-6-20.
 */
public class DownRouteHandler extends Handler {
//    private final static String preffix_ume = "/preview/";
    private final static String preffix_updown = "/down/";


    /**
     * 过滤新闻路径url
     *
     * @param target
     * @param request
     * @param response
     * @param isHandled
     */
    @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response,
            boolean[] isHandled) {
        /**
         * "/down/modulename/bizuuid/filename.jpg"
         */
        String preffix = "";
        String rex = "(\\w+)/(\\w+)/(\\w+)\\.(\\w+)";
        //UME用路由
//        if (target.startsWith(preffix_ume)) {
//            preffix = preffix_ume;
//        }else {
            //TODO 系统公共上传下载路由 需要单独提取出来
            preffix = preffix_updown;
//        }
        rex = preffix + rex;
        Pattern pattern = Pattern.compile(rex);
        Matcher matcher = pattern.matcher(target);
        DownLoadFileParse iu = new DownLoadFileParse();
        boolean status = matcher.find();
        if (status) {
            iu.setModulename(matcher.group(1));//modulename
            iu.setBizuuid(matcher.group(2));//bizuuid
            iu.setFilename(matcher.group(3));//文件名称（不含后缀）
            iu.setSuffix(matcher.group(4));//后缀名 .jpg .abc
        }
        if (status) {
            target = makeUrlParam(iu, preffix);
            next.handle(target, request, response, isHandled);
        }
        else {
            next.handle(target, request, response, isHandled);
        }
    }


    /**
     * 拼成访问UpandDownController loadimg方法的url<br/>
     * 说明：因jfinal的url生成方式比较特殊，完全依照restful约定<br/>
     * 参数之间用"-"间隔<br/>
     * 例如：/xxx/xxx/param1-param2-param3-param4<br/>
     *
     * @param hiu
     * @return
     */
    private String makeUrlParam(DownLoadFileParse hiu, String preffix) {
        StringBuilder sb = new StringBuilder(preffix);
        sb.append(hiu.getModulename()).append("-");
        sb.append(hiu.getBizuuid()).append("-");
        sb.append(hiu.getFilename()).append("-");
        sb.append(hiu.getSuffix());
        return sb.toString();
    }

}

